package com.wxxymakers.cklabrecruit.utils;

import com.wxxymakers.cklabrecruit.entity.RegisterInfo;
import io.github.biezhi.ome.OhMyEmail;
import io.github.biezhi.ome.SendMailException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @AUTHOR soft
 * @DATE 2018/11/17 15:17
 * @DESCRIBE 邮件发送工具
 */
@Slf4j
@Component
public class EmailUtils {

    @Value("${email.qq}")
    private String qq;    // 群
    @Value("${email.link}")
    private String link;  // 加群链接
    @Value("${email.from}")
    private String from;  // 发送方名称

    @Async
    public void send(String title, String from, String to, String content) {
        try {
            OhMyEmail.subject(title)
                    .from(from)
                    .to(to)
                    .html(content)
                    .send();
        } catch (SendMailException e) {
            log.error("邮件发送失败！{}", e.getMessage());
        }
    }

    /**
     * 发送报名成功通知
     * @param to 接收人邮箱
     * @param stuName 接收人姓名
     */
    @Async
    public void sendRegSuccess(String to, String stuName) {
        String builder = "<div><div>" + "<p>" +
                stuName +
                ", 恭喜你报名成功！</p>" +
                "<p>欢迎加群讨论: <a href='" +
                link + "'>" + qq + "</a></p>" +
                "</div><hr><div style='text-align: right; font-size: 12px; color: #666;'>" +
                "<p>软件开发创客实验室</p><p>" +
                DateUtils.getTime() +
                "</p></div></div>";
        this.send("报名成功通知！", from, to, builder);
    }

    public String getRealEmail(String template, RegisterInfo info, String returnUrl) {
        String replace = template.replace("{name}", info.getName())
                .replace("{stuId}", info.getStuId())
                .replace("{grade}", info.getGrade())
                .replace("{group}", info.getGroup().getName())
                .replace("{time}", DateUtils.getTime())
                .replace("{return}", returnUrl);
        return replace;
    }

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.debug", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.timeout", "10000");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.host", "smtp.office365.com");
        OhMyEmail.config(props, "developer@wismo.tech", "$WismoDev18");

        EmailUtils utils = new EmailUtils();
        utils.send("智慧猫", "121212", "643876945@qq.com", "8888");
    }
}
